package com.service.service;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import java.io.IOException;

public class TrapService {

    //通过snmp4j发送trap消息
    public static void main(String[] args) {
        try {
            TrapService sender = new TrapService();
            sender.init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void init() throws IOException {
        // 创建UDP传输映射 0.0.0.0/162 表示监听162号端口
        TransportMapping transport = new DefaultUdpTransportMapping();
        Snmp snmp = new Snmp(transport);
        transport.listen();

        //开始发送trap命令
        // 创建Trap PDU
        PDU pdu = new PDU();
        pdu.setType(PDU.V1TRAP);
        pdu.add(new VariableBinding(SnmpConstants.sysUpTime, new OctetString("1024")));
        pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID("1.3.6.1.6.3.1.1.5.0")));
        pdu.add(new VariableBinding(SnmpConstants.sysName, new OctetString("TrapSender")));
        pdu.add(new VariableBinding(SnmpConstants.sysLocation, new OctetString("Location")));

        // 设置Trap目标 向本地的162号端口fa消息
        CommunityTarget target = new CommunityTarget();
        target.setCommunity(new OctetString("public"));
        target.setAddress(GenericAddress.parse("udp:127.0.0.1/9001"));
        target.setVersion(SnmpConstants.version1);
        target.setRetries(2);
        target.setTimeout(5000);

        // 发送Trap 这里是把消息发送给了 udp:127.0.0.1/162 这个端口
        ResponseEvent response = snmp.send(pdu, target);
        System.out.println("send success : data is "+pdu);
        //System.out.println("Trap sent: " + response.getResponse());
    }

}
